package com.gzc.just.play.last.war.common.registry.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.gzc.just.play.last.war.common.distributed.ServiceInstance;
import com.gzc.just.play.last.war.common.registry.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PreDestroy;
import java.util.Properties;

/**
 * Nacos服务注册实现
 */
@Component("lastWarNacosServiceRegistry")
public class NacosServiceRegistry implements ServiceRegistry {
    
    private static final Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);
    
    private NamingService namingService;
    
    @Value("${spring.cloud.nacos.discovery.server-addr:127.0.0.1:8848}")
    private String serverAddr;
    
    @Value("${spring.cloud.nacos.discovery.namespace:}")
    private String namespace;
    
    @Value("${spring.cloud.nacos.discovery.group:DEFAULT_GROUP}")
    private String group;
    
    @Value("${spring.cloud.nacos.discovery.enabled:true}")
    private boolean enabled;
    
    /**
     * 初始化Nacos命名服务
     */
    private void initNamingService() throws NacosException {
        if (!enabled) {
            logger.info("Nacos service discovery is disabled");
            return;
        }
        
        if (namingService == null) {
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            if (namespace != null && !namespace.isEmpty()) {
                properties.put("namespace", namespace);
            }
            namingService = NamingFactory.createNamingService(properties);
            logger.info("Nacos naming service initialized: serverAddr={}, namespace={}", serverAddr, namespace);
        }
    }
    
    @Override
    public void register(ServiceInstance instance) throws Exception {
        if (!enabled) {
            logger.debug("Nacos discovery disabled, skip registration");
            return;
        }
        
        initNamingService();
        
        Instance nacosInstance = convertToNacosInstance(instance);
        String serviceName = instance.getServiceName();
        
        namingService.registerInstance(serviceName, group, nacosInstance);
        logger.info("Registered service instance: serviceName={}, instanceId={}, host={}, port={}", 
                   serviceName, instance.getInstanceId(), instance.getHost(), instance.getPort());
    }
    
    @Override
    public void deregister(ServiceInstance instance) throws Exception {
        if (!enabled || namingService == null) {
            return;
        }
        
        String serviceName = instance.getServiceName();
        namingService.deregisterInstance(serviceName, group, instance.getHost(), instance.getPort());
        logger.info("Deregistered service instance: serviceName={}, host={}, port={}", 
                   serviceName, instance.getHost(), instance.getPort());
    }
    
    @Override
    public void update(ServiceInstance instance) throws Exception {
        if (!enabled) {
            return;
        }
        
        // Nacos通过重新注册来更新实例信息
        register(instance);
    }
    
    @Override
    public void setStatus(ServiceInstance instance, boolean healthy) throws Exception {
        if (!enabled || namingService == null) {
            return;
        }
        
        // Nacos通过更新实例健康状态
        Instance nacosInstance = convertToNacosInstance(instance);
        nacosInstance.setHealthy(healthy);
        
        String serviceName = instance.getServiceName();
        namingService.registerInstance(serviceName, group, nacosInstance);
        logger.info("Updated service instance status: serviceName={}, instanceId={}, healthy={}", 
                   serviceName, instance.getInstanceId(), healthy);
    }
    
    @PreDestroy
    @Override
    public void close() {
        if (namingService != null) {
            try {
                namingService.shutDown();
                logger.info("Nacos naming service closed");
            } catch (Exception e) {
                logger.error("Error closing Nacos naming service", e);
            }
        }
    }
    
    /**
     * 将ServiceInstance转换为Nacos Instance
     */
    private Instance convertToNacosInstance(ServiceInstance instance) {
        Instance nacosInstance = new Instance();
        nacosInstance.setInstanceId(instance.getInstanceId());
        nacosInstance.setIp(instance.getHost());
        nacosInstance.setPort(instance.getPort());
        nacosInstance.setHealthy(true);
        nacosInstance.setEnabled(true);
        nacosInstance.setWeight(1.0);
        nacosInstance.setMetadata(instance.getMetadata());
        return nacosInstance;
    }
}
